var rtqWindowGroup = new Util.WindowGroup(document.body, {}, {});

var workspaceManagerClass = function(){
    this.gridUnit = 0;
    this.toolbar = null;
    this.saveErrorCount = 0;
    this.isSaving = false; //is saving components
    var self = this;
    var gMenu = null;
    var selectedWsIdInMenu = -1;
    var myWorkSpaceListData = [];
    var wsFontSize = "fs-normal";
    var menuIsRearrange = false;
    var wsProfiles = GOLBAL_DATA.WorkspaceProfileList;
    var gMenuItemMaximum = 15
    //this.dWorkspaceList = $("#rtq-gsetting [idkey=wsMenu]");
    this.arrWorkspaceList = [];
    this.open = function(wsId){
        var tab = WorkspaceTabs.getTabById(wsId);
        if (wsId == "_wsListMore") {
            var filelist={};
            filelist[QS_Lang.workspace["gb_mwork"]]=self.generateMoreMenuData();
            workspaceManager.openOpenFileWin(filelist, function(el){
                workspaceManager.exec('wsList', el.getAttribute('cmd'));
            });
        }
        else 
            if (tab) {
                tab.active();
            }
            else {
                tab = createWorkspace(gWsList[wsId]);
                //tab.show();
                //tab.ws.profile.close = null;
                gWsList[tab.id].profile.close = null;
                if (tab.id > -10000) {
                    DBHelper.saveWorkspace(gWsList[tab.id], tab.id, self.getTabWidgets(tab));
                    Terminal.setConfig({
                        LastActiveWorkspace: tab.id,
                        openWorkspaceIdList: WorkspaceTabs.getIdList()
                    });
                }
	        //UserTrace
	        Qs_UserTrace.OperateComponent(Qs_UserTrace.Group.Activity, Qs_UserTrace.Source.Workspace, Qs_UserTrace.Oper.Open, tab.txt, tab.id, "Open an exist workspace.");
            }
        if (tab != null) {
            WorkspaceTabs.changeToTab(tab);
        }
    };
    this.createWorkSpace=function(workspaceProfile){
		return createWorkspace(workspaceProfile);
	};
    var createWorkspace = function(workspaceProfile){
        //add by yuntao
        var toolbarLinkEl = $('#rtq-gsetting a.toolbar');
        //		self.toolbar.settingShow=(typeof Terminal.getConfig('HideToolbar')!='undefined')?(!Terminal.getConfig('HideToolbar')):true;
        //		self.toolbar.contentShow=(typeof Terminal.getConfig('HideToolbarContent')!='undefined')?(!Terminal.getConfig('HideToolbarContent')):false;
        //		self.toolbar.menuSelectIndex=(typeof Terminal.getConfig('HideToolbarMenuIndex')!='undefined')?Terminal.getConfig('HideToolbarMenuIndex'):0;
        
        workspaceProfile.txt = workspaceProfile.profile.name;
        if (workspaceProfile.id <= -10000) {
            //workspaceProfile.closable = false;
        }
        WorkspaceTabs.addTab(workspaceProfile);
        var tab = WorkspaceTabs.getTabById(workspaceProfile.id);
		//tab.id = workspaceProfile.id;
        tab.modules = null;
        tab.showHelper = (typeof workspaceProfile.profile.showHelper != 'undefined') ? workspaceProfile.profile.showHelper : false;
        tab.timerSubscribe = 0;
        tab.isStopSubscribe = false;
        if (self.toolbar) {
            tab.toolbarBtn = $('<a href="#" class="toolbar-btn' + (self.toolbar.settingShow ? ' toolbar-btn-open' : '') + '">T</a>').appendTo(tab.menu).click(function(e){
                if (self.toolbar.settingShow) {
                    tab.toolbarBtn.removeClass('toolbar-btn-open');
                    self.handleToolbar('hide');
                }
                else {
                    tab.toolbarBtn.addClass('toolbar-btn-open');
                    self.handleToolbar('show');
                }
                return false;
            });
            if (workspaceProfile.id > -10000 && workspaceProfile.id <= 0) {
                tab.toolbarBtn.hide();
            }
        }
        tab.loadModules = function(){//build module
            if (!tab.modules) {
                RtqDesktop.buildModules(wsWidgets[tab.id], tab);
            }
            else {
                //show module
                var win = null;
                for (var k in tab.modules) {
                    win = tab.modules[k].win;
                    if (win && win.widget) {
                        win.widget.pause = false;
                    }
                }
            }
            
            if (tab.showHelper == true) {
				if (LayoutHelper != null) {
					LayoutHelper.setWorkspace(tab);
					LayoutHelper.show();
				}
            }
            else {
				if (LayoutHelper != null) {
					LayoutHelper.hide();
				}
                
            }
        };
        tab.windowGroup = new Util.WindowGroup(tab.panel, {}, {});
        return tab;
    };
    
    this.openWorkspaceManager = function(){
        var id = idService.newMinusId();
        gWsList[id] = {
            id: id,
            profile: {
                name: QS_Lang.workspace["wsm_addtab"],
                showHelper: true
            }
        };
        wsWidgets[id] = [];
        var tab = createWorkspace(gWsList[id]);
        tab.showHelper = true;
        tab.active();
        
        if (LayoutHelper == null) {
            LayoutHelper = new layoutHelper();
        }
        LayoutHelper.setWorkspace(tab);
        LayoutHelper.show();
        //save(tab);
    };
    this.renameWorkspace = function(wsid, callback){
        if (wsid == 'undefined') {
            Util.message(QS_Lang.text["wsrename"]);
        }
        Util.prompt(QS_Lang.workspace["wsm_renamewstitle"], function(name){
            gWsList[wsid].profile.name = name;
            var tab = WorkspaceTabs.getTabById(wsid);
            if (tab != null) {
                save(tab, false, false, function(){ //save workspace
                    $(tab.menu).find("span").text(name);
                    tab.txt = name;
					
					//add ellipsis style
					tab.menu.ellipsis();
					
                    WorkspaceTabs.reBindTabList();
                    if (callback != null && typeof(callback) != 'undefined') {
                        callback(gWsList[wsid]);
                    }
                    Util.message(QS_Lang.text["wsrenamesuccess"]);
                });
            }
            else {
                Terminal.showLoading();
                self.isSaving = true;
                DBHelper.saveWorkspaceName(gWsList[wsid], wsid, function(r){
                    if (r == '') { //timeout
                        self.saveErrorCount++;
                        if (self.saveErrorCount >= 2) {
                            Util.confirm(QS_Lang.text["wssavetimeout"], function(b){
                                if (b) {
                                    window.location = 'logout.jsp?tmpid=' + QS_UserTID;
                                }
                            }, {
                                title: QS_Lang.workspace["wsm_saveerrortitle"]
                            });
                        }
                        Terminal.hideLoading();
                        return;
                    }
                    r = $.evalJSON(r); //database error
                    if (r && r.wsprofile && r.wsprofile.id) {
                        gWsList[wsid] = r.wsprofile;
                        if (callback != null && typeof(callback) != 'undefined') {
                            callback(r.wsprofile);
                        }
                        Util.message(QS_Lang.text["wsrenamesuccess"]);
                    }
                    else {
                        Util.message(QS_Lang.text["wsrename"]);
                    }
                    Terminal.hideLoading();
                    self.isSaving = false;
                });
            }
            //UserTrace
            Qs_UserTrace.OperateComponent(Qs_UserTrace.Group.Activity, Qs_UserTrace.Source.Workspace, Qs_UserTrace.Oper.Rename, name, wsid, String.format("old name is {0}.", gWsList[wsid].profile.name));
            initGMenuData();
            gMenu.reBindSecondLevelMenu("openws", myWorkSpaceListData, 2);
        }, {
            validateMethod: function(name){
                if (name.length < 1 || $.trim(name) == '') {
                    Util.message(QS_Lang.text["wsinput"]);
                    return false;
                }
                if (!QS_Validator.test(name, 'name')) {
                    return false;
                }
                var keyWordResult=QS_Validator.testKeyWord(name,'workspacename');
                if(!keyWordResult.valid){
                    Util.message(String.format(QS_Lang.text["wsrenamedefault"],keyWordResult.promprStr));
                    return false;
                }
                if (self.hasWorkspaceName(name)) {
                    Util.message(QS_Lang.text["wsname"]);
                    return false;
                }
                return true;
            }
        });
    }
    this.saveAsHandler = function(){
		if (wsSaveasObj == null) {
            wsSaveasObj = new workspaceSaveasWindow();
        }
        wsSaveasObj.show(null,function(name, cid){
            var id = idService.newMinusId();
            gWsList[id] = {
                id: id,
                profile: {
                    name: name
                }
            };
            var widgets = self.getTabWidgets(WorkspaceTabs.currentTab).widgets.list;
            widgets.delIds = [];
            wsWidgets[id] = [];
            if (widgets) {
                $.extend(true, wsWidgets[id], widgets);
                for (var i = 0, l = wsWidgets[id].length; i < l; i++) {
                    wsWidgets[id][i].id = idService.newMinusId();
                }
            }
            
            var tab = createWorkspace(gWsList[id]);
            tab.active();
            save(tab, false, false, function(){ //save workspace
                save(tab, true, false); //save components
                if (cid != 0) {
                    workspaceManagement["addWorkspaceLabel"](tab.id, cid);
                }
            });
        });
    };
    
    // get current widgets profile from tab, not from "wsWidgets"
    this.getTabWidgets = function(tab){
        var tab = tab || WorkspaceTabs.currentTab;
        if (tab) {
            //var modules={}; //deep copy for modules
            //$.extend(true,modules,tab.modules);
            var widgets = [];
            var m, config, box;
            for (var k in tab.modules) {
                m = tab.modules[k];
                if (!m) 
                    continue;
                config = {};
                $.extend(true, config, m.config);
                with (config) {
                    profile.x = m.win.cfg.left;
                    profile.y = m.win.cfg.top;
                    profile.w = m.win.cfg.width;//box.width; //why not m.win.width
                    profile.h = m.win.cfg.height;//box.height; //why not m.win.height
                    profile.state = m.win.getState();//box.state 0:minimize 1:normal 2:maximize
                    profile.layerIndex = m.win.getIndex();//box.index
                    profile.name = m.win.getTitle();
                    profile.oldBox = m.win.cfg.oldBox;//for restore
                    profile.active = m.win.getActive();//for active and inactive
                    profile.locked = m.win.cfg.locked;
                }
                if (m.win.widget && typeof(m.win.widget.saveConfig) == "function") {
                    try {
                        config.profile.widget = m.win.widget.saveConfig();
                    } 
                    catch (ex) {
                        if (!config.profile.widget) 
                            config.profile.widget = {};
                    }
                }
                widgets.push(config);
            }
            
            return {
                delIds: wsWidgets[tab.id] ? wsWidgets[tab.id].delIds : [],
                widgets: {
                    id: tab.id,
                    list: widgets
                }
            };
        }
    }
    
    this.hasWorkspaceName = function(name){
        for (var k in gWsList) {
            if (!gWsList[k].isDeleted&&gWsList[k].id > 0 && name == gWsList[k].profile.name) {
                return true;
            }
        }
        return false;
    };
    
    function save(Tab, Feedback, Capture, successCallback){
        var tab = Tab || WorkspaceTabs.currentTab;
        var feedback = Feedback === false ? false : true;
        var capture = Capture || false;
        var wsID = tab.id;
        if (!tab || gWsList[wsID].profile.showHelper || gWsList[wsID].isDeleted) {
            return;
        }
        Terminal.showLoading();
        if (wsID == WorkspaceTabs.currentTab.id) {
            self.toolbar.showSaveLoading();
        }
        
        if (wsID <= -10000) {
            if (feedback) 
                Util.alert(QS_Lang.text["wssavedefault"]);
        }
        else 
            if (wsID < 0) { // add a new work space.
                DBHelper.insertWorkspace(gWsList[wsID], function(r){
                    r = eval("(" + r.replace(/"/g, "'") + ")");
                    
                    gWsList[wsID].id = r.id;
                    gWsList[wsID].updateTime = r.updateTime || '';
                    gWsList[r.id] = gWsList[wsID];
                    delete gWsList[wsID];
                    wsWidgets[r.id] = wsWidgets[wsID];
                    delete wsWidgets[wsID];
                    tab.id = wsID = r.id;
					
					//add ellipsis style
					tab.menu.ellipsis();
					
                    WorkspaceTabs.reBindTabList();
                    
                    Terminal.setConfig({
                        LastActiveWorkspace: tab.id,
                        wsFontSize: wsFontSize,
                        openWorkspaceIdList: WorkspaceTabs.getIdList()
                    });
                    self.toolbar.updateLastDateTime(wsID);
                    Terminal.hideLoading();
                    
                    if (feedback) {
                        Util.message(QS_Lang.text["wssavedsuccessfully"]);
                    }
                    if (typeof(successCallback) == "function") {
                        successCallback();
                    }
                    self.changGMenu(wsID, 0); // insert a item to open submenu in global menu.
                    
					updateScreenshot(wsID, false);
                });
            }
            else {
                var currWorkspace = self.getTabWidgets(tab);
                gWsList[tab.id].profile.showHelper = tab.showHelper;
                //			if(self.toolbar){//add by yuntao
                //				self.toolbar.setConfig(tab.id);
                //			}
                self.isSaving = true;
                if (currWorkspace.widgets) {
                    DBHelper.saveWorkspace(gWsList[tab.id], wsID, currWorkspace.widgets, function(r){
                        if (r == '') { //timeout
                            self.saveErrorCount++;
                            if (self.saveErrorCount >= 2) {
                                Util.confirm(QS_Lang.text["wssavetimeout"], function(b){
                                    if (b) {
                                        window.location = 'logout.jsp?tmpid=' + QS_UserTID;
                                    }
                                }, {
                                    title: QS_Lang.workspace["wsm_saveerrortitle"]
                                });
                            }
                            Terminal.hideLoading();
                            return;
                        }
                        
                        r = $.evalJSON(r); //database error
                        if (!r || !r.workspace || !r.workspace.id) {
                            Util.message(QS_Lang.text["wssaveerror"]);
                            Terminal.hideLoading();
                            return;
                        }
                        
                        wsWidgets[r.workspace.id] = wsWidgets[wsID];
                        tab.id = r.workspace.id;
                        
                        var len = r.widgets.list.length;
                        var modules = {};
                        var widgets = currWorkspace.widgets.list; 
                        for (var i = 0; i < len; i++) {   // change by Jacye. 
                            var id = r.widgets.list[i];
                            var oldId = widgets[i].id;   
                            widgets[i].id = id;
                            var m = tab.modules[oldId];
                            if (m) {
                                m.id = id;
                                m.config.id = id;
                                m.win.moduleId = id;
                                if(id!=oldId&&m.win.widget.type == 1){  // chart component has register the old id to chart data manager. so need reserve the original id.
                                    push.proxy.unregister(m.win.widget);  //unregister the old id from data manager;
                                } 
                                m.win.widget.id = id;
                                if (id!=oldId&&(m.win.widget.type == 1||m.win.widget.type == 3)) { // chart and quicktake need reregister the component
                                    push.proxy.register(m.win.widget); // register new id to data manager.
                                }
                                modules[id] = m;
                            }
                        }
                        wsWidgets[wsID] = widgets;						
                        lastModules = tab.modules = modules;
                        gWsList[tab.id] = r.wsprofile;
						if (wsID == WorkspaceTabs.currentTab.id) {
							DBHelper.saveCurrentWorkspaceProfile(wsID,$.toJSON({"list":widgets}),gWsList[wsID].updateTime || '');
						}
                        self.toolbar.updateLastDateTime(tab.id);
                        Terminal.hideLoading();
                        if (feedback) {
                            Util.message(QS_Lang.text["wssavedsuccessfully"]);
                        }
                        
                        //capture screenshot
                        if (capture) {
                                updateScreenshot(wsID, false);
                        }
                        if (typeof(successCallback) == "function") {
                            successCallback();
                        }
                        self.isSaving = false;
                    });
                }
                // delete widgets
                if (currWorkspace.delIds && currWorkspace.delIds.length > 0) {
                    deleteWidgets(tab.id, currWorkspace.delIds, function(s){
                        var r = eval("(" + s + ")");
                        if (!r && !r.list) {
                            currWorkspace.delIds = null;
                        }
                    });
                }
            }
		//usagetracking
        Qs_UserTrace.Serialize();
    };
    this.saveWorkspace = function(){
        var args = arguments;
        var tab = args[0];
        var wsid = tab.id;
        if (wsid < 0) {  //unsave workspace
        if (wsSaveasObj == null) {
            wsSaveasObj = new workspaceSaveasWindow();
        }
        wsSaveasObj.show(tab.txt,function(name,id){
                gWsList[wsid].profile.name = name;
                tab.txt = name;
                tab.menu.find('span').html(name);
                save(tab, false, false, function(){ //save workspace
                    save(tab, true, false); //save components
                    if(id!=0){
                        workspaceManagement["addWorkspaceLabel"](tab.id,id);
                    }
                    if(args[3]){
                        args[3](); //callback
                    }
                });
            });
//            Util.prompt('Workspace name:', function(name){
//                gWsList[wsid].profile.name = name;
//                tab.txt = name;
//                tab.menu.find('span').html(name);
//                
//                save(tab, false, false, function(){ //save workspace
//                    save(tab, true, false); //save components
//                    if(args[3]){
//                        args[3](); //callback
//                    }
//                });
//            }, {
//                validateMethod: function(name){
//                    if (name.length < 1) {
//                        Util.message(QS_Lang.text["wsinput"]);
//                        return false;
//                    }
//                    if ($.trim(name) == '') {
//                        Util.message(QS_Lang.text["wsinput"]);
//                        return false;
//                    }
//                    if (workspaceManager.hasWorkspaceName(name)) {
//                        Util.message(QS_Lang.text["wsname"]);
//                        return false;
//                    }
//                    if (!QS_Validator.test(name, 'name')) {
//                        return false;
//                    }
//                    return true;
//                }
//            })
        }
        else {
            save.apply(this, args);
        }
    };
    
    //this.saveComponent = save;
    this.autoSave = function(tab){
        tab = tab || WorkspaceTabs.currentTab;
        if (Terminal.getConfig('TurnOffAutoSave')) {
            return;
        }
        if (typeof(QS_DetachWorkspaceID) != "undefined" || !WorkspaceTabs || self.isSaving) {
            return;
        }// detach window not auto-save
        var old = $.toJSON(wsWidgets[tab.id]);
        var curr = self.getTabWidgets(tab);
        if (tab.id > 0) {
            if (curr.widgets && curr.widgets.list) {
                if (old != $.toJSON(curr.widgets.list)) {
                    save(tab, false);
                }
            }
        }
    };
    
    this.remove = function(id, excuteCallback,callback){
        excuteCallback = excuteCallback == false ? false : true;
        if (id <= -10000) {
            Util.message(QS_Lang.text["wsdeldefault"]);
            return;
        }
        var tab = WorkspaceTabs.getTabById(id);
        if (tab) {
            var modules = tab.modules;
            if (!modules) 
                for (var k in modules) {
                    if (modules[k].win) 
                        modules[k].win.close();
                }
        }
        gWsList[id].isDeleted = true;
        if (id > 0) {
            Terminal.showLoading();
            deleteWorkspace(id, function(r){ // delete workspace from DB and refresh the terminal.
                if (!r || r.indexOf("true", 0) < 0) {
                    Util.message(QS_Lang.text["wsdelerror"]);
                    return;
                }
                if (tab) {
                    WorkspaceTabs.removeTab(tab, excuteCallback);
                    if (gWsList) {
                        gWsList[id] = null;
                        delete gWsList[id];
                        self.changGMenu(id, 2); // change  the global menu.
                    }
					if(getLocalStorageByKey('QS_CurWsId')==id){
						removeLocalStorage(['QS_CurWs','QS_CurWsId','QS_CurWs_UpdatedTime']);
					}
                }
				if(typeof(callback)=="function"){
					callback();
				}
                Terminal.hideLoading();
            });
        }
        else {//don't save
            WorkspaceTabs.removeTab(tab, excuteCallback);
            if (gWsList) {
                gWsList[id] = null;
                delete gWsList[id];
                self.changGMenu(id, 2);// change  the global menu.
            }
        }
		//UserTrace
	    Qs_UserTrace.OperateComponent(Qs_UserTrace.Group.Activity, Qs_UserTrace.Source.Workspace, Qs_UserTrace.Oper.Delete, gWsList[id].profile.name, id, String.format("Delete this {0}saved workspace",id<0?"un":""));
            
    }
    // add widget to current workspace
    this.addWidgetToCurrentWs = function(ty, ticker, profile){  // ty: the widget type.
        if (!profile) {
            profile = getDefaultProfileByType(ty);
            //profile.widget = {};
        }
        if (ticker != null && ticker.length > 0) {
            profile.widget.ticker = ticker;
        }
        return RtqDesktop.addModule(profile);
    };
    
    this.handleToolbar = function(event, isSave){
        if (event == 'hide') {
            self.toolbar.hideSettingBar(isSave);
        }
        if (event == 'show') {
            self.toolbar.showSettingBar();
        }
    };
    
    window.rtt1 = null;
    window.rtt2 = null;
    this.init = function(){
        var gridUnit = Terminal.getConfig('gridUnit');
        if (gridUnit && parseInt(gridUnit, 10) > 0) {
            this.gridUnit = gridUnit;
            $('#workspace').addClass('rtq-workspace-grid-' + gridUnit);
        }
        
        workspaceManager_Dialogs.call(this);
        
        //connect push service
        initWorkspaceToolbar();
        initWsList();
        initToolbar();
        var toolbarLinkEl = $('#rtq-gsetting a.toolbar');
        if (self.toolbar.settingShow == true && typeof QS_DetachWorkspaceID == 'undefined') {
            self.handleToolbar('show');
            if (self.toolbar.contentShow == true) {
                self.toolbar.showContentBar();
            }
            else {
                self.toolbar.hideContentBar();
            }
        }
        else {
            self.handleToolbar('hide', false);//not save
        }
        setTimeout(function(){
            if (QSPC.checkPermission(5) && Terminal.getConfig('HideTickerTape') == false) {
                initTickerTape();
            }
            //holdRelease();
        }, 1000);
        
        Terminal.autoSave(function(){
            self.autoSave(WorkspaceTabs.currentTab);
        });
        
        if (!Terminal.getConfig('HideTipsDialog') && typeof QS_DetachWorkspaceID == 'undefined') {
            this.openTipsDialog(QSTIPs);
        }
        if (!Terminal.getConfig('HideLicenseDialog') && typeof QS_DetachWorkspaceID == 'undefined') {
			QS_LOADER.LoadModule({id: "-1"}, function(){
				self.openLicenseDialog(QSLICENSE.Content);
			});
		}
    };
    
    function initWsList(){
        WorkspaceTabs = null;
        //set opening def workspaces
        var openingDefWS = Terminal.getConfig('activeDefWorkspaces') ||
        {};
        for (var w in gWsList) {
            if (w <= -10000 && openingDefWS[w]) {
                gWsList[w].profile.close = 0;
            }
        }
        //merge def and user workspaces
        if (wsProfiles && wsProfiles.list.length > 0) {
            for (var i = 0; i < wsProfiles.list.length; i++) {
                var ws = {};
                ws.id = wsProfiles.list[i].id;
                ws.updateTime = wsProfiles.list[i].updateTime;
                ws.profile = eval("(" + wsProfiles.list[i].profile + ")");
				if(ws.profile.screenShotURL){
                    ws.profile.screenShotURL = ws.profile.screenShotURL.replace(/^https?:/,"");
                }
				ws.label = wsProfiles.list[i].label||"";
                gWsList[wsProfiles.list[i].id] = ws;
            }
        }
        
        //for screenshot David 20100108
        if (typeof QS_DetachWorkspaceID != 'undefined' && gWsList[QS_DetachWorkspaceID]) {
            //copy the workspace profile
            var ws = {}, widgets = {};
            ws.id = gWsList[QS_DetachWorkspaceID].id;
            ws.profile = gWsList[QS_DetachWorkspaceID].profile; // it is a json string.
            //clear other workspace profile
            gWsList = null;
            delete gWsList;
            gWsList = {};
            gWsList[QS_DetachWorkspaceID] = ws;
            if (typeof(QS_Detaching) != "undefined" && window.opener) {// detach
                $.extend(true, widgets, window.opener.wsWidgets[QS_DetachWorkspaceID]); // fixed issue in IE
                //widgets = $.extend(window.opener.wsWidgets[QS_DetachWorkspaceID]); // fixe bug in IE.QS_DetachWorkspaceWidgets; // all components in workspace.
            }
            else { // capture.
                widgets = QS_DetachWorkspaceWidgets.list;
            }
            if (widgets) {
                wsWidgets[QS_DetachWorkspaceID] = [];
                if (typeof QS_DetachComponentID != 'undefined') {// if specified component id. detach
                    for (var i in widgets) {
                        if (QS_DetachComponentID == widgets[i].id) {
                            if (typeof(QS_Detaching) != "undefined") {//detach
                                var profile = widgets[i].profile;
                                if (QS_DetachWorkspaceID < 0) { // default workspace
                                    //var p = $.extend(window.opener.QS_DefaultWsDetachWidgets[QS_DetachComponentID]);
                                    $.extend(true, profile.widget, window.opener.QS_DefaultWsDetachWidgets[QS_DetachComponentID]); // 
                                }
                            }
                            else 
                                if (typeof(QS_DetachCapture) != "undefined") {//detach Capture
                                    var profile = $.evalJSON(widgets[i].profile);
                                }
                            profile.x = 0;
                            profile.y = 0;
                            profile.w = $(document.body).width();
                            profile.h = $(document.body).height();
                            wsWidgets[QS_DetachWorkspaceID].push({
                                id: widgets[i].id,
                                profile: profile
                            });
                            break;
                        }
                    }
                    GOLBAL_DATA.terminalGlobalProfile.HideTickerTape = true; // hide the ticker tap.
                    QS_DetachWindowResizable = true;
                }
                else { // capture.
                    for (var i in widgets) {
                        wsWidgets[QS_DetachWorkspaceID].push({
                            id: widgets[i].id,
                            profile: $.evalJSON(widgets[i].profile)
                        });
                    }
                }
            }
        }
        start();
        self.createTabDropDownMenu();
    };
    
    function start(){
        WorkspaceTabs = new Util.TabMenu($('#workspace')[0], [], {
            onActive: function(tab){
                //add by yuntao
                if (self.toolbar.settingShow) {
                    tab.toolbarBtn.addClass('toolbar-btn-open');
                }
                else {
                    tab.toolbarBtn.removeClass('toolbar-btn-open');
                }
                self.toolbar.setToolbarStatus(tab.id);
                //load profile
                if (!wsWidgets[tab.id]) {
                    //tabs.setDisabled(true);
                    getWidgets(tab.id, function(s){
						if(s=='error'){
							return;
						}
                        var r = $.evalJSON(s);
                        var len = r.list.length;
                        if (r && len > 0) {
                            wsWidgets[tab.id] = [];
                            for (var i = 0; i < len; i++) {
                                wsWidgets[tab.id].push({
                                    id: r.list[i].id,
                                    profile: typeof r.list[i].profile=='string'?$.evalJSON(r.list[i].profile):r.list[i].profile
                                });
                            }						
                        }
                        else {
                            wsWidgets[tab.id] = [];
                        }
						DBHelper.saveCurrentWorkspaceProfile(tab.id,s,gWsList[tab.id].updateTime || '');
                        tab.loadModules();
                        //tabs.setDisabled(false);
                    });
                }
                else {
					if (tab.id > -10000) {
						DBHelper.saveCurrentWorkspaceProfile(tab.id,$.toJSON({list: wsWidgets[tab.id]}),gWsList[tab.id].updateTime || '');			
					}else{
						DBHelper.saveCurrentWorkspaceProfile('','','');
					}
                    tab.loadModules();
                }
                
                //save Terminal config
                if (GOLBAL_DATA.terminalGlobalProfile.LastActiveWorkspace != tab.id && typeof QS_Capture == 'undefined') {
                    //save opening def workspace
                    var openingDefWS = {};
                    for (var i = 0, l = WorkspaceTabs.tabs.length; i < l; i++) {
                        //get all opening Def WS
                        if (WorkspaceTabs.tabs[i].id <= -10000 && !WorkspaceTabs.tabs[i].isClose) {
                            openingDefWS[WorkspaceTabs.tabs[i].id] = !WorkspaceTabs.tabs[i].isClose;
                        }
                    }
                    Terminal.setConfig({
                        LastActiveWorkspace: tab.id,
                        activeDefWorkspaces: openingDefWS,
                        openWorkspaceIdList: WorkspaceTabs.getIdList()
                    });
                }
                // bindWidgetList(tab.menu);
                //self.bindDropDownMenutoTab(tab);
                //re-subscribe
                clearTimeout(tab.timerSubscribe);
                tab.timerSubscribe = -1;
                if (tab.isStopSubscribe) {
                    var win;
                    for (var k in tab.modules) {
                        if (win = tab.modules[k].win) {
                            if (win.widget && win.widget.reSubscribe) {
                                win.widget.reSubscribe();
                            }
                        }
                    }
                    tab.isStopSubscribe = false;
                }
                self.bindDropDownMenutoTab(tab);
                self.changGMenu(tab.id, 1); // change the select state in global main menu.
                if(QS_MessageSender!=null) QS_MessageSender.hide();
            },
            onDeActive: function(tab){
                var win = null;
                for (var k in tab.modules) {
                    if (win = tab.modules[k].win) {
                        if (win.widget) {
                            win.widget.pause = true;
                        }
                    }
                }
                //stop subscribe
                clearTimeout(tab.timerSubscribe);
                tab.timerSubscribe = -1;
                tab.timerSubscribe = setTimeout(function(){
                    var win;
                    for (var k in tab.modules) {
                        if (win = tab.modules[k].win) {
                            if (win.widget && win.widget.stopSubscribe) {
                                win.widget.stopSubscribe();
                            }
                        }
                    }
                    tab.isStopSubscribe = true;
                }, 60 * 1000);
                //self.toolbar.setConfig(tab.id);
                self.autoSave(tab);
                //unbindWidgetList(tab.menu);
                self.unbindDropDownMenutoTab(tab);
            },
            beforeClose: function(tab){
                self.beforeClose(tab);
            },
            afterClose: function(tab){
                self.afterClose(tab);
            },
			onAddTab:function(){				
				workspaceManager.openWorkspaceManager();
			},
            afterRearrange: function(tab){
                Terminal.setConfig({
                    openWorkspaceIdList: WorkspaceTabs.getIdList()
                });
                menuIsRearrange = false;
            },
            beforeRearrange: function(tab){
                menuIsRearrange = true;
            }
        }, {
            width: 138,
			marginRightWidth:68,
			plusSymbol:true,
            autoResize: false,
            switchType: 'position',
            customCls: 'workspace-tab',
            tabsList: true,
            autoFixtoText: true,
            rearrange: true
        });
		
		
        //append right side tablist to body
        $(WorkspaceTabs.tabList.dom).addClass('workspace-tablist').appendTo(document.body);
        WorkspaceTabs.setPanelOutSize(xDesktopW, xDesktopH);
		
        var oldself = self;
        var openedWSIdList = Terminal.getConfig('openWorkspaceIdList');
        if (typeof(QS_Capture) != "undefined" && QS_Capture == true && $.inArray(QS_DetachWorkspaceID, openedWSIdList) < 0) {
            openedWSIdList.push(QS_DetachWorkspaceID);
        }
        if (openedWSIdList) {
            for (var i = 0; i < openedWSIdList.length; i++) {
                wid = openedWSIdList[i];
                if (!gWsList[wid] || (gWsList[wid].profile.close && gWsList[wid].profile.close == '1' && typeof QS_DetachWorkspaceID == 'undefined')) {
                    continue;
                }
                createWorkspace(gWsList[wid]);
            }
        }
        else {
            for (var w in gWsList) {
                if (gWsList[w].profile.close && gWsList[w].profile.close == '1' && typeof QS_DetachWorkspaceID == 'undefined') {
                    continue;
                }
                createWorkspace(gWsList[w]);
            }
        }
        
		//add ellipsis style
		$(WorkspaceTabs.dom).find(".workspace-tab-menus li").ellipsis();
		
        //active tab
        if (WorkspaceTabs.tabs.length > 0) {
            if (GOLBAL_DATA.terminalGlobalProfile['LastActiveWorkspace']) {
                var idx = 0;
                for (var i = 0; i < WorkspaceTabs.tabs.length; i++) {
                    if (WorkspaceTabs.tabs[i].id == GOLBAL_DATA.terminalGlobalProfile['LastActiveWorkspace']) {
                        idx = i;
                        break;
                    }
                }
                WorkspaceTabs.changeToTab(WorkspaceTabs.tabs[idx]);
            }
            else {
                WorkspaceTabs.changeToTab(WorkspaceTabs.tabs[0]);
                //here we set the toolbar show/hide;
            
            }
        }
        else {
            self.openWorkspaceManager();
        }        
        getAlertFromDB(); //get alerts
    }
    
    function afterLogout(){
    }
    
    this.exec = function(cmd, item){
        var changeFontSize = function(size){
            Terminal.setConfig({
                wsFontSize: wsFontSize
            });
			//$(document.body).css('font-size', size + 'px');
			$(document.body)[0].className=wsFontSize;
            if (typeof($sender) != "undefined") 
                $sender.parent().addClass('on').siblings().removeClass('on');
        };
        if (item && typeof(item.data) != "undefined" && typeof(item.data.openws) != "undefined" && item.data.openws) {
            this.open(cmd);
        }
        switch (cmd) {
            case "newws":
                var id = idService.newMinusId();
                gWsList[id] = {
                    id: id,
                    profile: {
                        name: QS_Lang.workspace["wsm_dwsname"]
                    }
                };
                wsWidgets[id] = [];
                var tab = createWorkspace(gWsList[id]);
                tab.active();
				if(LayoutHelper ==null){
					LayoutHelper = new layoutHelper();
                    LayoutHelper.desktop = $('body');
				}
                LayoutHelper.setWorkspace(tab);
                LayoutHelper.createWorkspace();
                break;
            case "wsmanager":
                self.openWorkspaceManager();
                break;
            case "savews":
				if (WorkspaceTabs.currentTab.id > -10000) {
					self.saveWorkspace(WorkspaceTabs.currentTab, true, true);
				}
				else {
					self.saveAsHandler();
				}
                break;
			case 'share':
				if(QS_MessageSender==null) QS_MessageSender=new MessageSender();
				QS_MessageSender.open("workspace",WorkspaceTabs.currentTab.id,null);
				break;
            case "saveasws":
				self.saveAsHandler();
                break;
            case "delws":
				Util.confirm(QS_Lang.text["wsdelconfirm"], function(b){
					if (b) {
						self.remove(WorkspaceTabs.currentTab.id);
					}
				});
                break;
            case "wsList":
                this.open(item);
                gMenu.changeItemClass(parseInt(item), null, "rtq-ratio-off", false, true);
                break;
            case "alert":
                workspaceManager.openAlertSetting();
                break;
            case "toolbar":
                if (item.el.text() == QS_Lang.workspace["gb_mbarshow"]) {
                    self.handleToolbar('hide');
                    WorkspaceTabs.currentTab.toolbarBtn.removeClass('toolbar-btn-open');
                }
                else {
                    self.handleToolbar('show');
                    WorkspaceTabs.currentTab.toolbarBtn.addClass('toolbar-btn-open');
                }
                break;
            case "tickertape":
                if (item.el.text() == QS_Lang.workspace["gb_mtapshow"]) {
                    rtt1.hide();
                    rtt2.hide();
                    var tts = push.proxy.getAllRegistedTickerTapes();
                    for (var i = 0; i < tts.length; i++) {
                        tts[i].pause = true;
                    }
                    Terminal.setConfig({
                        HideTickerTape: true
                    });
                }
                else {
                    if (rtt1 && rtt2) {
                        rtt1.show();
                        rtt2.show();
                        var tts = push.proxy.getAllRegistedTickerTapes();
                        for (var i = 0; i < tts.length; i++) {
                            tts[i].pause = false;
                        }
                    }
                    else {
                        initTickerTape();
                    }
                    Terminal.setConfig({
                        HideTickerTape: false
                    });
                }
				RtqDesktop.layout();
				self.resizeMaxWindow();
                break;
            case "fs-verylarge":
                changeFontSize(16);
                break;
            case "fs-large":
                wsFontSize = "fs-large";
                changeFontSize(13);
                break;
            case "fs-normal":
                wsFontSize = "fs-normal";
                changeFontSize(11);
                break;
            case "fs-small":
                wsFontSize = "fs-small";
                changeFontSize(10);
                break;
            case "fs-verysmall":
                changeFontSize(9);
                break;
            case "about":
                Util.alert('<br>Morningstar QuoteSpeed 2.0<br><br>', {
                    title: QS_Lang.workspace["wsm_wsversiontitle"]
                });
                break;
			case "message":
                if (!QS_messageViewer) {
					QS_messageViewer = new messageViewer({});
				}
				else {
				    QS_messageViewer.open();
				}
                break;
            case "en_us":
            case "de_us":
                this._setMutilanguage(cmd);
                break;
			case "screener":
			    if(!QS_Terminal_Screener){
					QS_Terminal_Screener=new QS_Screener(null);
					QS_Terminal_Screener.init(
                        {   needOperBar:true,
                            dragable:true,
                            isAPI:false,
                            navSize:5,
                            clickTicker:false,
                            width:700,
                            height:500,
                            canExport:true,
                            operateBarConfig:{
                                "default":false,"pdf":false,"idr":false
                            }
                        });
				}else{
					QS_Terminal_Screener.show();
				}
				break;
            case "help":
                // window.open('help/Morningstar%20QuoteSpeed%20Quick%20Start%20Guide.pdf');
                //workspaceManager.openOnlineSupportDialog("support.jsp?theme=" + QS_Theme);
            	workspaceManager.openOnlineSupportDialog("support.jsp?theme="+QS_Theme+"&userId="+QS_UserID+"&userEmail="+QS_UserNAME);
                break;
            case "tips":
                this.openTipsDialog();
                break;
            case "feedback":
                window.location = 'mailto:qs@morningstar.com?subject=QuoteSpeed Feedback';
                break;
            case "logout":
                window.location = 'logout.jsp?tmpid=' + QS_UserTID;
                break;
            case "delay":
            case "bats":
            case "mix":
            case "fast":
            case "slow":
            case "slower":
            case "slowest":
                changeDataConfiguration(cmd);
                break;
            case "autoSave":
                if (item.el.text() == 'Turn On Auto-saving') {
                    Terminal.setConfig({
                        TurnOffAutoSave: true
                    });
                }
                else {
                    Terminal.setConfig({
                        TurnOffAutoSave: false
                    });
                }
                break;
        }
        RtqDesktop.layout();
    };
    function changeDataConfiguration(v){
        if (QS_DataType == v) {
            return;
        }
        if (WorkspaceTabs.currentTab.id > 0) {
            workspaceManager.saveWorkspace(false, false, false, function(o){
                window.location = URLparam({"datatype":v});
            });
        }
        else {
            window.location = URLparam({"datatype":v});
        }
    };
    this._setMutilanguage=function(lan){
        if(lan!=QS_LangTag){
            this.autoSave(WorkspaceTabs.currentTab);
            Terminal.setConfig({"Language": lan},function(){
                window.location = URLparam({"lang":lan});
            });
        }
    };
    function URLparam(param){
        var urlCfg={}, location= window.location,__url=location.search;

        if (__url != "" && __url.length > 0) {
            __url = __url.substr(__url.indexOf("?")+1);
        }
        var carr = __url.split("&");
        for (var i = 0; i < carr.length; i++) {
            if($.trim(carr[i])=="") continue;
            var item = carr[i].split("=");
            urlCfg[$.trim(item[0])] = $.trim(item[1]);
        }
        for(var key in param){
            urlCfg[$.trim(key)]=param[key];
        }
        return "index.jsp?"+$.param(urlCfg);
    };
    function initGMenuData(){ // rebind the gMenu data.
        var list = gWsList, idx = 0;
        myWorkSpaceListData = [];
        for (var w in list) {
            if (list[w].profile.showHelper) {
                continue;
            }
            if (idx < gMenuItemMaximum) {
                myWorkSpaceListData.push({
                    txt: list[w].profile.name,
                    val: list[w].id,
                    type: "ratio",
                    openws: true
                });
            }
            else {
                myWorkSpaceListData.push({
                    type: "separator"
                });
                myWorkSpaceListData.push({
                    txt: QS_Lang.workspace["gb_mmore"],
                    val: "_wsListMore",
                    type: "",
                    openws: true
                });
                break;
            }
            idx++;
        }
    }
	function _getGlobalWorkspaceMenuData(){
        var qslang=QS_Lang.workspace;
		var workspaceSubMenuData = [{
					txt: qslang["gb_mnew"],
					val: "newws"
				}, {
					txt: qslang["gb_mopen"],
					val: "openws",
					subMenu: myWorkSpaceListData
				}]
		if(!WorkspaceTabs.currentTab.showHelper){
			workspaceSubMenuData.push(!QSPC.checkPermission(20)?null:{
				txt: qslang["gb_mshare"],
				val: 'share'
			});
			workspaceSubMenuData.push({
				txt: qslang["gb_msave"],
				val: "savews"
			});
			workspaceSubMenuData.push({
				txt: qslang["gb_msavea"],
				val: "saveasws"
			});
			workspaceSubMenuData.push({
				txt: qslang["gb_mdel"],
				val: "delws"
			});
		}
		return workspaceSubMenuData;
	}
    function initToolbar(){
		//add Settings and Add buttons to workspace toolbar
        var qslang=QS_Lang.workspace;
        var workspaceSettings='<div id="rtq-gsetting"><a mname="fileMenu" class="rtf-hd-setting" href="javascript:void(0)">File </a></div>';
		var workspaceMessage='<div class="qs-message-note"><a href="#"><span></span></a></div>';
       $('body').append(workspaceSettings+workspaceMessage); 
		$('.qs-start-loading').addClass('off');
		//added by wind 20110310
        initGMenuData();
        wsFontSize = Terminal.getConfig("wsFontSize");
		var fontSizeNum= 11;
		if(wsFontSize=="fs-large"){
			fontSizeNum = 13
		}else if(wsFontSize=="fs-small"){
			fontSizeNum = 10
		}
		//$(document.body).css('font-size', fontSizeNum + 'px');
		$(document.body)[0].className=wsFontSize;
        var dataType = Terminal.getConfig("dataConfiguration");
		var dataConfigMenu=[{
                txt: qslang["gb_mstream"],
                val: "",
                selectable:false,
                subMenu: [{
                    txt: qslang["gb_msdelay"],
                    type:"ratio",
                    selected:QS_DataType=="delay",
                    val: "delay"
                }, {
                    txt: qslang["gb_msreal"],
                    type:"ratio",
                    selected:QS_DataType=="mix",
                    val: "mix"
                }]
            }];
			if(checkPullPermission()){
				dataConfigMenu=dataConfigMenu.concat([{
	                txt: String.format(qslang["gb_mdfast"],PULL_DATA_RATE["fast"]),
	                type:"ratio",
	                selected:QS_DataType=="fast",
	                val: "fast"
	            },{
	                txt: String.format(qslang["gb_mdslow"],PULL_DATA_RATE["slow"]),
	                type:"ratio",
	                selected:QS_DataType=="slow",
	                val: "slow"
	            },{
	                txt: String.format(qslang["gb_mdslower"],PULL_DATA_RATE["slower"]),
	                type:"ratio",
	                selected:QS_DataType=="slower",
	                val: "slower"
	            },{
	                txt: String.format(qslang["gb_mdslowest"],PULL_DATA_RATE["slowest"]),
	                type:"ratio",
	                selected:QS_DataType=="slowest",
	                val: "slowest"
                }]);                        
			}
        var gMenuData = [{
				txt: qslang["gb_mwork"],
				val: "workspace",
				selectable: false,
				subMenu: _getGlobalWorkspaceMenuData()
			}, {
				type: 'separator'
			}, {
				txt: qslang["gb_mtoolbar"],
				val: "toolbars",
				selectable: false,
				subMenu: [{
					txt: Terminal.getConfig('HideToolbar') == false ? qslang["gb_mbarhide"]:qslang["gb_mbarshow"],
					type: 'switch',
					val: 'toolbar',
					sTxt: [qslang["gb_mbarshow"], qslang["gb_mbarhide"]]
				}, {
					txt: Terminal.getConfig('HideTickerTape') == false ? qslang["gb_mtaphide"]:qslang["gb_mtapshow"],
					type: 'switch',
					val: 'tickertape',
					sTxt: [qslang["gb_mtapshow"], qslang["gb_mtaphide"]]
				}]
			}, {
				txt: qslang["gb_mfont"],
				val: "",
				selectable: false,
				subMenu: [{
					txt: qslang["gb_mlar"],
					type: "ratio",
					selected: wsFontSize == "fs-large",
					val: "fs-large"
				}, {
					txt: qslang["gb_mnor"],
					type: "ratio",
					selected: true,
					selected: wsFontSize == "fs-normal",
					val: "fs-normal"
				}, {
					txt: qslang["gb_msma"],
					type: "ratio",
					selected: wsFontSize == "fs-small",
					val: "fs-small"
				}]
			}, {
				txt: qslang["gb_mdata"],
				val: "",
				selectable: false,
	//            subMenu: [{
	//                txt: "Delay",
	//                type: "ratio",
	//                selected: QS_DataType == "delay",
	//                val: "delay"
	//            }, {
	//                txt: "Delay and BATS",
	//                type: "ratio",
	//                selected: QS_DataType == "mix",
	//                val: "mix"
	//            }]
				subMenu: dataConfigMenu
			}, {
				txt: Terminal.getConfig('TurnOffAutoSave') ? qslang["gb_mautoon"] : qslang["gb_mautooff"],
				val: "autoSave",
				type: 'switch',
				sTxt: [qslang["gb_mautoon"], qslang["gb_mautooff"]]
			}, {
				type: 'separator'
			}, {
				txt: qslang["gb_malert"],
				val: "alert"
			}, {
				type: 'separator'
			}, {
				txt: qslang["gb_mmessage"],
				val: "message",
				selectable: true/*,
				subMenu: [{
					txt: "Notify when received",
					type: "ratio",
					selected: wsFontSize == "fs-large",
					val: "fs-large"
				},{
					txt: "Notify when Log in",
					type: "ratio",
					selected: wsFontSize == "fs-large",
					val: "fs-large"
				}]*/
			},QSPC.checkPermission(28)?{
                txt: qslang["gb_mlanguage"],
                val: "lan",
                selectable: true,
                subMenu: [{
                    txt: "English",
                    type: "ratio",
                    selected : QS_LangTag == "en_us",
                    val: "en_us"
                },{
                    txt: "Deutsch",
                    type: "ratio",
                    selected : QS_LangTag == "de_us",
                    val: "de_us"
                }]
            }:null,
			QSPC.checkPermission(25)?{
				txt: qslang["gb_mscreener"],
				val: "screener",
				selectable: true
			}:null,
			{
				txt: qslang["gb_msupport"],
				val: "help",
				selectable: true
			}, {
				txt: qslang["gb_mtip"],
				val: "tips"
			}, {
				txt: qslang["gb_mabout"],
				val: "about"
			}, {
				type: 'separator'
			}, {
				txt: qslang["gb_mexit"],
				val: "logout"
			}];
        var $gsettingMenu = $("#rtq-gsetting")
        gMenu = new Util.CascadeMenu($gsettingMenu, {
            display: false,
            isTraceMouse: false,
            autoHide: false
        }, gMenuData, {
            onClick: function(item){
                if (item != null) {
                    workspaceManager.exec(item.data.val, item);
                }
                gMenu.hide();
            }
        });
        
        var timer = null;
        $gsettingMenu.hover(function(e){
			gMenu.reBindSecondLevelMenu("workspace",_getGlobalWorkspaceMenuData(),1);
            gMenu.show();
            clearTimeout(timer);
        }, function(e){
            clearTimeout(timer);
            timer = setTimeout(function(){
                gMenu.hide();
            }, 500);
        });
        
        $righttool = $("#rtq-righttool").find('a').click(function(){
            workspaceManager.exec(this.getAttribute('value'));
        });
		
		//workspaceMessage
		$message = $('.qs-message-note').bind('click',function(){
			if (!QS_messageViewer) {
				QS_messageViewer = new messageViewer({});
			}
			else {
				QS_messageViewer.open();
			}
		});
        
    }
    //added by yuntao
    function initWorkspaceToolbar(){
        if (typeof(QS_WorkspaceToolbar) == "function") {
            self.toolbar = new QS_WorkspaceToolbar();
        }
        
    }
    
    function initTickerTape(){
        rtt1 = new RTQ_TickerTape($('.rtt-tape').eq(0)[0], 3, tktp1dat, 'rtt1');
        rtt2 = new RTQ_TickerTape($('.rtt-tape').eq(1)[0], 6, tktp2dat, 'rtt2');
        rtt1.type = 5;
        rtt2.type = 5; //for register in push.proxy
        rtt1.id = 101;
        rtt2.id = 102;
        push.proxy.register(rtt1);
        push.proxy.register(rtt2);
        $('.rtt-tape').show();
        //holdRelease();
    }
    
    this.onSymbolSelected = function(line){
    
    };
    this.generateMoreMenuData = function(){
        var list = []
        for (var w in gWsList) {
            if (gWsList[w].profile.showHelper) { // remove the "new workspace template"
                continue;
            }
			if(w > -10000&&gWsList[w].profile.close == "1"){//remove closed and unSaved workspace
				continue;
			}
            list.push({
                text: gWsList[w].profile.name,
                cmd: gWsList[w].id
            });
        }
        return list;
    };
    this.changGMenu = function(wsId, op){
        if (op == 1 && gMenu != null) { // select the new workspace.
            gMenu.changeUIState(wsId, "openws", true);
            gMenu.changeUIState(selectedWsIdInMenu, "openws", false);
            selectedWsIdInMenu = wsId;
        }
        else 
            if (op == 0) { // add a new workspace.
                var ws = gWsList[wsId];
                if (ws && ws.profile) {
                    selectedWsIdInMenu = wsId;
                    if (myWorkSpaceListData.length == gMenuItemMaximum) {
                        myWorkSpaceListData.push({
                            type: "separator"
                        });
                        myWorkSpaceListData.push({
                            txt: QS_Lang.workspace["gb_mmore"],
                            val: "_wsListMore",
                            type: "",
                            openws: true
                        });
                        gMenu.reBindSecondLevelMenu("openws", myWorkSpaceListData, 2);
                    }
                    else 
                        if (myWorkSpaceListData.length >= (gMenuItemMaximum + 2)) {// has more item.
                            return;
                        }
                        else { // less than gMenuItemMaximum items.
                            myWorkSpaceListData.push({
                                txt: ws.profile.name,
                                val: wsId,
                                type: "ratio",
                                openws: true,
                                selected: Terminal.getConfig("LastActiveWorkspace") == wsId
                            });
                            gMenu.reBindSecondLevelMenu("openws", myWorkSpaceListData, 2);
                        }
                }
            }
            else 
                if (op == 2) { // remove a workspace.
                    var olg = myWorkSpaceListData.length;
                    for (var i = 0; i < olg; i++) {
                        if (myWorkSpaceListData[i].val == wsId) {
                            myWorkSpaceListData.splice(i, 1);
                            break;
                        }
                    }
                    if (olg == (gMenuItemMaximum + 2) && myWorkSpaceListData.length <= (gMenuItemMaximum + 1)) { // rebind the menu data.
                        initGMenuData();
                    }
                    gMenu.reBindSecondLevelMenu("openws", myWorkSpaceListData, 2);
                    selectedWsIdInMenu = Terminal.getConfig("LastActiveWorkspace");
                    gMenu.changeUIState(selectedWsIdInMenu, "openws", true);
                }
    };
    
    /* add by yuntao for replace the tab Menu*/
    this.tabDDMenuData_Components = [];
    this.activeWidget = function(key){
        var modules = getCurrModules();
        var m = modules[key];
        if (m) {
            if (m.win.hidden == true) 
                m = modules[key] = RtqDesktop.createModule(m.config);
            else 
                m.win.show();
        }
    };
    this.beforeClose = function(tab){
        if (tab.id <= -10000 && tab.modules) {
            for (k in tab.modules) {
                if (tab.modules[k].win) 
                    tab.modules[k].win.clear();
            }
            tab.modules = null;
            for (var i = 0; i < wsWidgets[tab.id].length; i++) { //remove added cpns
                if (wsWidgets[tab.id][i].id > -10000) {
                    wsWidgets[tab.id][i] = null;
                    wsWidgets[tab.id].splice(i, 1);
                }
            }
        }
        
        if (tab.id > -10000 && !gWsList[tab.id].profile.showHelper) {
            if (gWsList[tab.id]) {
                gWsList[tab.id].profile.close = "1";
            }
            
            if (tab.id < 0) {  //unsave workspace
                tab.closable = false;
                Util.confirm(QS_Lang.workspace["wsm_comfirmsavews"], function(b){
                    if(b){
                        self.saveWorkspace(tab, false, false, function(){
                            tab.close();
                        });
                    }else{
                        WorkspaceTabs.removeTab(tab, false);
                        WorkspaceTabs.tabs[0].active();
                    }
                    tab.closable = true;
                }, {
                    closeCallback: function(){
                        tab.closable = true;
                        return;
                    }
                });
            }else{
                if (!Terminal.getConfig('TurnOffAutoSave')) {
                    DBHelper.saveWorkspace(gWsList[tab.id], tab.id, self.getTabWidgets(tab));
                }
            }
        }
    };
    this.afterClose = function(tab){
        var tabCount = 0;
        for (var i = 0, l = WorkspaceTabs.tabs.length; i < l; i++) {
            if (!WorkspaceTabs.tabs[i].isClose) {
                tabCount++;
            }
        }
        if (tabCount < 1) {
            self.openWorkspaceManager(); //open "New Workspace" tab if all tabs have been del
        }
        self.workspaceTabDropDownMenu.hide();
		//UserTrace
	    Qs_UserTrace.OperateComponent(Qs_UserTrace.Group.Activity, Qs_UserTrace.Source.Workspace, Qs_UserTrace.Oper.Close, tab.txt, tab.id, "Close this workspace.");
    };
    this.closeTab = function(tab){
        var tab = tab || WorkspaceTabs.currentTab;
        this.beforeClose(tab);
        this.afterClose(tab);
        tab.close();
        tab.menu.unbind('mouseover.tabwsddl').unbind('mouseout.tabwsddl');
    };
    this.lockWorkspace = function(lockCmd, tab){
        var tab = tab || WorkspaceTabs.currentTab;
        if (!gWsList[tab.id].profile) {
            gWsList[tab.id].profile = {};
        }
        gWsList[tab.id].profile.isLock = lockCmd;
        this.setWorkspaceWidgetsLock(lockCmd, tab);
        workspaceManager.saveWorkspace(tab, false, false);
    };
    this.setWorkspaceWidgetsLock = function(lockCmd, tab){
        for (var k in tab.modules) {
            m = tab.modules[k];
            if (m.win) {
                m.win.setLock(lockCmd);
            }
        }
    };
    this.getTabDDMenuData = function(tab){
        var qslang=QS_Lang.workspace;
        tab = tab || WorkspaceTabs.currentTab;
        if (!tab) {
            return [];
        }
        var modules = tab.modules;
        this.tabDDMenuData_Components = [];
        for (var k in modules) {
            name = modules[k].win.title;
            this.tabDDMenuData_Components.push({
                txt: name,
                val: 'windows',
                key: k,
                selectable: true
            });
        }
        var compSize = this.tabDDMenuData_Components.length;
        var type = tab.id < 0 ? 'def' : '';
        
        if (!gWsList[tab.id].profile) {
            gWsList[tab.id].profile = {};
        }
        var isLock = gWsList[tab.id].profile.isLock;
        return [compSize == 0 ? null : {
            txt: qslang["ws_window"],
            val: 'windows',
            subMenu: this.tabDDMenuData_Components
        }, {
            txt: qslang["ws_addwindow"],
            val: 'addWindows'
        }, {
            type: "separator"
        }, type == 'def' || isLock ? null : {
            txt: qslang["ws_save"],
            val: 'save'
        }, {
            txt: qslang["ws_saveas"],
            val: 'saveas'
        }, type == 'def' || isLock ? null : {
            txt: qslang["ws_rename"],
            val: 'rename'
        }, type == 'def' || isLock ? null : {
            txt: qslang["ws_delete"],
            val: 'delete'
        },type == 'def'||!QSPC.checkPermission(20)? null : {
            txt: qslang["ws_share"],
            val: 'share'
        }, type == 'def' ? null : {
            txt: gWsList[tab.id].profile.isLock ? qslang["ws_unlock"] : qslang["ws_lock"],//Terminal.getConfig('HideToolbar')==false?"Lock":"UnLock",
            type: 'switch',
            val: 'lockws',
            sTxt: [qslang["ws_lock"], qslang["ws_unlock"]]
        }, {
            txt: qslang["ws_close"],
            val: 'close'
        }];
    };
    this.createTabDropDownMenu = function(){
        this.workspaceTabDropDownMenu = new Util.CascadeMenu($('#rtwls')[0], {
            display: false,
            isTraceMouse: false,
            autoHide: true
        }, this.getTabDDMenuData(), {
            onClick: function(item){
                switch (item.data.val) {
                    case 'windows':
                        self.activeWidget(item.data.key);
                        break;
                    case 'addWindows':
                        self.toolbar.showSettingBar();
                        self.toolbar.showContentBar();
                        WorkspaceTabs.currentTab.toolbarBtn.addClass('toolbar-btn-open');
                        break;
                    case 'save':
                        self.saveWorkspace(WorkspaceTabs.currentTab, true, true);
                        break;
                    case 'saveas':
                        self.saveAsHandler();
                        break;
				    case 'share':
				    	if(QS_MessageSender==null) QS_MessageSender=new MessageSender();
				        QS_MessageSender.open("workspace",WorkspaceTabs.currentTab.id,null);
				        break;
                    case 'rename':
                        self.renameWorkspace(WorkspaceTabs.currentTab.id, null);
                        break;
                    case 'delete':
                        Util.confirm(QS_Lang.text["wsdelconfirm"], function(b){
                            if (b) {
                                self.remove(WorkspaceTabs.currentTab.id);
                            }
                        });
                        break;
                    case 'lockws':
                        if (item.el.text() == QS_Lang.workspace["ws_unlock"]) {
                            self.lockWorkspace(true);
                        }
                        else {
                            self.lockWorkspace(false);
                        }
                        
                        break;
                    case 'close':
                        self.closeTab();
                        break;
                }
				self.workspaceTabDropDownMenu.hide();
            }
        });
    };
    var showTimeOutObj;
    this.rebindTabDropDownMenu = function(tab){
        var menuData = this.getTabDDMenuData(tab);
        this.workspaceTabDropDownMenu.reBind(menuData, true);
        var xy = tab.menu.position();
        self.workspaceTabDropDownMenu.setPosition(xy.left + 30, xy.top + 23);
        clearTimeout(showTimeOutObj);
        showTimeOutObj = setTimeout(function(){
            self.workspaceTabDropDownMenu.show();
        }, 200); //delay for slide to current tab
    };
    this.bindDropDownMenutoTab = function(tab){
        var tab = tab || WorkspaceTabs.currentTab;
        tab.menu.bind('mouseover.tabwsddl', function(){
            if (tab.id < 0 && tab.id > -10000) {
                return;
            }
            if (menuIsRearrange) {
                return;
            }
            clearTimeout(self.workspaceTabDropDownMenu._timeOut);
            self.rebindTabDropDownMenu(tab);
        }).bind('mouseout.tabwsddl', function(e){
            clearTimeout(showTimeOutObj);
			var target=$(e.relatedTarget);
			if(typeof target=='undefined'||target==null){
				return;
			}
			var className=target.attr("class");
			if(className==null){
				return;
			}
            if (className.indexOf("rtq-menu") == -1) {
                self.workspaceTabDropDownMenu.hide();
            }
        });
    };
    this.unbindDropDownMenutoTab = function(tab){
        tab.menu.unbind('.tabwsddl');
    };
    this.checkSaved = function(){//Judge whether workspace will save?
        if (typeof(QS_DetachWorkspaceID) != "undefined" || !WorkspaceTabs) {
            return;
        }// detach window not auto-save
        //tab = tab||WorkspaceTabs.currentTab;
        var tab = tab || WorkspaceTabs.currentTab;
        var old = $.toJSON(wsWidgets[tab.id]);
        if (tab.id > 0) {
            var curr = self.getTabWidgets(tab);
            if (curr.widgets && curr.widgets.list) {
                var list = [];
                $.extend(true, list, wsWidgets[tab.id]);
                $.extend(true, list, curr.widgets.list);
                
                if (old != $.toJSON(list)) {
                    return false;
                }
            }
        }
        return true;
    };
    this.addTickerToUnLockWindow = function(ticker){
        if (!ticker && ticker == '') {
            return;
        }
        var ms = getCurrModules(), w;
        for (var k in ms) {
            w = ms[k].win.widget;
            if (w.type == 0 || w.type == 11 || w.type == 12 || w.type == 13 || w.type == 14) {
                continue;
            }
            if (w && typeof(w.acceptTicker) == "function" && ((!w.chartComponent && !w.lock) || (w.chartComponent && !w.chartComponent.lock))) {
                w.acceptTicker(ticker);
            }
        }
    };
    this.setGridSnapConfig = function(gridUnit){
        var snapToGrid = false, config = {
            gridUnit: gridUnit
        };
        WorkspaceTabs.currentTab.windowGroup.setConfig(config);
        if (this.gridUnit != gridUnit) {
            $('#workspace').removeClass('rtq-workspace-grid-' + this.gridUnit).addClass('rtq-workspace-grid-' + gridUnit);
            this.gridUnit = gridUnit;
            Terminal.setConfig({
                gridUnit: gridUnit
            });
        }
    };
    this.getGridUnit = function(){
        return this.gridUnit;
    };
	this.resizeMaxWindow=function(){
		var ms = getCurrModules(), w;
        for (var k in ms) {
		   w=ms[k].win;
		   if(w&&w.getState()==2){
		   	  w.maxmize();
		   }
		}
	};
};
workspaceManagerClass.prototype.testMethod = function(){
};

